package com.across.connect.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.across.connect.home.MyUserHome;
import com.across.connect.model.MyUser;
import com.across.connect.util.CommonConst;
import com.across.connect.util.CookieManager;
import com.across.connect.util.XnConnect;

public abstract class AbstractAction extends Action{
	
	private MyUser host = null;
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){

		try {
			//从Cookie中获取SessionKey和校内ID
			String sessionKey = CookieManager.getInstance().getCookie(request, XnConnect.getXiaoneiApiKey()+"_session_key");
			int xnuid = 0;
			if (!StringUtils.isBlank(sessionKey)) {
				xnuid = Integer.parseInt(CookieManager.getInstance().getCookie(request, XnConnect.getXiaoneiApiKey()+"_user"));
				//将用户ID和SessionKey保存到一个本地MAP中
				//在调用REST接口时需要SessionKey
				XnConnect.setXiaoneiSessionKey(xnuid, sessionKey);
			}
			//从Cookie获取站点自己的用户ID
			String _id = CookieManager.getInstance().getCookie(request, CommonConst.COOKIE_USER_ID);
			if (_id == null && xnuid > 0) {
				//用户没有在站点登录但有校内ID 这种情况可以认为用户通过Connect登录
				//将Connect用户信息保存到本地数据库中
				host = MyUserHome.getInstance().createFromXiaoneiUID(xnuid);
				CookieManager.getInstance().saveCookie(response, CommonConst.COOKIE_USER_ID, String.valueOf(host.getId()));
			}
			else if (_id == null) {
				//如果没有任何Cookie信息则认为用户没有通过站点登录或者Connect登录
				response.sendRedirect("login.do");
				return null;
			}
			else {
				//从数据库获取一条用户信息
				host = MyUserHome.getInstance().getMyUserByUserID(
						Integer.parseInt(_id));
				
				//如果发现这个用户记录有校内ID但没有站点ID则认为用户已经退出Connect登录了
				//出于安全考虑可以强迫用户重新登录
				if (xnuid == 0 && host.getXnuid() > 0) {
					CookieManager.getInstance().clearCookie(response,
							CommonConst.COOKIE_USER_ID, 0, "/");
					response.sendRedirect("login.do");
					return null;
				}
				//如果站点记录的用户信息与Connect登录的用户无法匹配，则应该迫使用户退出再让用户登录
				else if (xnuid > 0 && host.getXnuid() != xnuid) {
					response.sendRedirect("logout.do?logout=yes");
					return null;
				}
				if (host == null) {
					response.sendRedirect("login.do");
					return null;
				}
			}
			request.setAttribute("apiKey", CommonConst.XN_API_KEY);
			request.setAttribute("host", host);
			ActionForward af = handleLogic(mapping, request, response);
			return af;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	protected abstract ActionForward handleLogic(ActionMapping mapping,HttpServletRequest request,HttpServletResponse response) throws Exception;

	protected MyUser getHost() {
		return host;
	}
}